package com.kaiwukj.android.ufamily.mvp.ui.page.mine.settings

import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.facade.Postcard
import com.alibaba.android.arouter.facade.callback.NavigationCallback
import com.alibaba.android.arouter.launcher.ARouter
import com.hyphenate.chat.EMClient
import com.kaiwukj.android.mcas.integration.AppManager
import com.kaiwukj.android.ufamily.R
import com.kaiwukj.android.ufamily.app.base.review.BaseFragment
import com.kaiwukj.android.ufamily.app.constant.CodeLoginRouterUrl
import com.kaiwukj.android.ufamily.app.constant.ShieldListUrl
import com.kaiwukj.android.ufamily.mvp.helper.AccountStore
import com.kaiwukj.android.ufamily.mvp.helper.AppStore
import com.kaiwukj.android.ufamily.mvp.helper.TokenStore
import com.kaiwukj.android.ufamily.mvp.ui.page.account.login.vcode.LoginVCodeIndexActivity
import com.kaiwukj.android.ufamily.mvp.ui.page.sys.about.AboutUsFragment
import com.kaiwukj.android.ufamily.utils.MyDataCleanManager
import com.kaiwukj.android.ufamily.utils.ServiceHistoryStore
import com.kaiwukj.android.ufamily.utils.UserStore
import com.qmuiteam.qmui.widget.QMUILoadingView
import com.qmuiteam.qmui.widget.QMUITopBar
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog
import com.qmuiteam.qmui.widget.grouplist.QMUICommonListItemView
import com.qmuiteam.qmui.widget.grouplist.QMUIGroupListView
import com.zghl.mclient.client.ZghlMClient
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.fragment_setting.*


/**
 * Copyright © KaiWu Technology Company
 * @author Haife
 * @job Android Development
 * @company KW | 开物科技
 * @time 2019/7/17
 * @desc  服务评价
 */
class SettingFragment : BaseFragment() {

    private var hintDialog: QMUITipDialog? = null

    companion object {
        const val SETTING_FRAGMENT = "SETTING_FRAGMENT"
        fun newInstance(): SettingFragment {
            return SettingFragment()
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_setting
    }

    override fun initView() {
        //TODO("Not yet implemented")
    }

    override fun initData(savedInstanceState: Bundle?) {
        initBottomGroupView()
        //退出登录
        qbtn_login_out.setOnClickListener {
            //   mPresenter?.requestLoginOut()
            onLoginOut()
        }
    }


    /**
     * 初始化GroupList
     */
    private fun initBottomGroupView() {
        val finishDialog = QMUITipDialog.Builder(context)
                .setTipWord(getString(R.string.setting_clearing_cache_success))
                .create()
        val clearCacheItem = qui_group_list_setting.createItemView(getString(R.string.setting_clear_cache))
        clearCacheItem.accessoryType = QMUICommonListItemView.ACCESSORY_TYPE_CUSTOM
        val loadingViewContainer: View = LayoutInflater.from(context)
                .inflate(R.layout.custom_clear_cache_loading_layout, null)
        val cacheSizeTv = loadingViewContainer.findViewById<TextView>(R.id.tv_cache_size)
        val loadingView = loadingViewContainer.findViewById<QMUILoadingView>(R.id.load_view_cache)
        clearCacheItem.addAccessoryCustomView(loadingViewContainer)
        val aboutCompany = qui_group_list_setting.createItemView(getString(R.string.setting_about_company))
        aboutCompany.accessoryType = QMUICommonListItemView.ACCESSORY_TYPE_CHEVRON
        val reportSetting = qui_group_list_setting.createItemView(getString(R.string.setting_report))
        reportSetting.accessoryType = QMUICommonListItemView.ACCESSORY_TYPE_CHEVRON

        val cacheSize: String = MyDataCleanManager.getTotalCacheSize(context)
        cacheSizeTv.text = cacheSize

        val onClickListener = View.OnClickListener { v ->
            when (v) {
                clearCacheItem -> {
                    if (!MyDataCleanManager.getTotalCacheSize(context).contains("0.0")) {
                        hintDialog = QMUITipDialog.Builder(context).setTipWord(getString(R.string.setting_clearing_cache)).create()
                        hintDialog?.setCancelable(false)
                        MyDataCleanManager.clearAllCache(context)
                    } else {
                        showMessage(getString(R.string.setting_not_need_clear_cache))
                        return@OnClickListener
                    }

                    loadingView.visibility = View.VISIBLE
                    cacheSizeTv.visibility = View.GONE
                    hintDialog?.show()
                    loadingView.start()



                    Handler().postDelayed({
                        loadingView.stop()
                        cacheSizeTv.text = MyDataCleanManager.getTotalCacheSize(context)
                        loadingView.visibility = View.GONE
                        cacheSizeTv.visibility = View.VISIBLE
                        hintDialog?.dismiss()
                        finishDialog?.show()
                        Handler().postDelayed({
                            finishDialog?.dismiss()
                        }, 500)
                    }, 1500)

                }
                aboutCompany -> {
                    start(AboutUsFragment.newInstance())
                }
                reportSetting -> {
                    //屏蔽设置
                    //  start(ReportSettingFragment.newInstance())
                    ARouter.getInstance().build(ShieldListUrl)
                            .navigation()
                }
            }
        }

        clearCacheItem.setBackgroundColor(ContextCompat.getColor(mContext, R.color.white_color))
        reportSetting.setBackgroundColor(ContextCompat.getColor(mContext, R.color.white_color))
        aboutCompany.setBackgroundColor(ContextCompat.getColor(mContext, R.color.white_color))

        QMUIGroupListView.newSection(context)
                .setUseTitleViewForSectionSpace(false)
                .addItemView(clearCacheItem, onClickListener)
                .addItemView(reportSetting, onClickListener)
                .addItemView(aboutCompany, onClickListener)
                .addTo(qui_group_list_setting)
    }

    override fun onSupportVisible() {
        super.onSupportVisible()
        activity?.findViewById<QMUITopBar>(R.id.qtb_edit_mine_info)?.setTitle("设置")
    }


    private fun onLoginOut() {
        /*val intent = Intent()
        intent.setClass(context!!, LoginIndexActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        startActivity(intent)*/
        /*ARouter.getInstance().build(LoginIndexRouterUrl)
                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
                .navigation()*/
        /* val intent = Intent(activity!!, MainActivity::class.java)
         intent.putExtra("closeType", 2)
         startActivity(intent)*/

        subscribe(Observable.create<Int> {
            AppStore.clearAll()
            AccountStore.logout()
            UserStore.clearAll()
            TokenStore.clear()
            EMClient.getInstance().logout(true)
            ZghlMClient.getInstance().logout()
            ServiceHistoryStore.clear()
            it.onNext(1)
        }
                .doOnSubscribe { showLoading("正在注销...") }
                .doFinally { hideLoading() }
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    ARouter.getInstance().build(CodeLoginRouterUrl).navigation(activity, object : NavigationCallback {
                        override fun onLost(postcard: Postcard?) {
                        }

                        override fun onFound(postcard: Postcard?) {
                        }

                        override fun onInterrupt(postcard: Postcard?) {
                        }

                        override fun onArrival(postcard: Postcard?) {
                            AppManager.getAppManager().killAll(LoginVCodeIndexActivity::class.java)
                        }
                    })
                });

    }

    override fun post(runnable: Runnable?) {
    }

}
